<template>
  <div class="orders-management">
    <el-table
      v-if="ordersList"
      ref="ordersTableRef"
      :data="ordersList"
      style="width: 100%"
      v-loading="loading"
      border
      table-layout="fixed"
    >
      <el-table-column prop="ordersId" label="订单号" width="120" show-overflow-tooltip />
      <el-table-column prop="tradeNo" label="交易号" width="200" show-overflow-tooltip />
      <el-table-column prop="courseName" label="课程名称" show-overflow-tooltip />
      <el-table-column prop="userName" label="用户名" width="100" show-overflow-tooltip />
      <el-table-column prop="buyerPayAmount" label="支付金额" width="100" align="right">
        <template #default="{ row }">
          ¥{{ row.buyerPayAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="paymentChannel" label="支付方式" width="100">
        <template #default="{ row }">
          {{ row.paymentChannel === 'alipay' ? '支付宝' : row.paymentChannel }}
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.orderStatus)">
            {{ row.orderStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="primary" @click="handleDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="ordersList && ordersList.length > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="订单详情"
      width="600px"
    >
      <div class="order-detail" v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.ordersId }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ currentOrder.courseName }}</el-descriptions-item>
          <el-descriptions-item label="购买用户">{{ currentOrder.userName }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.buyerPayAmount }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ currentOrder.paymentChannel === 'alipay' ? '支付宝' : currentOrder.paymentChannel }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.orderStatus)">
              {{ currentOrder.orderStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ currentOrder.payTime || '-' }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="order-timeline">
          <h4>订单状态记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="(item, index) in getOrderTimeline(currentOrder)"
              :key="index"
              :timestamp="item.time"
              :type="item.type"
            >
              {{ item.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'OrdersManagementView',
  setup() {
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(0)
    const ordersList = ref([])
    const ordersTableRef = ref(null)
    const dialogVisible = ref(false)
    const currentOrder = ref(null)
    
    const getStatusType = (status) => {
      const types = {
        '支付成功': 'success',
        '取消订单': 'danger',
        '待支付': 'warning'
      }
      return types[status] || 'info'
    }

    const getOrderTimeline = (order) => {
      const timeline = [
        {
          time: order.createTime,
          content: '订单创建',
          type: 'primary'
        }
      ]
      
      if (order.orderStatus === '取消订单') {
        timeline.push({
          time: order.updateTime || order.payTime,
          content: '订单取消',
          type: 'danger'
        })
      } else if (order.payTime) {
        timeline.push({
          time: order.payTime,
          content: '支付完成',
          type: 'success'
        })
      }
      
      return timeline
    }

    const handleDetail = (row) => {
      currentOrder.value = row
      dialogVisible.value = true
    }
    
    const fetchOrders = async () => {
      try {
        loading.value = true
        const response = await request({
          url: '/ordersService/ordersController/selectAllOrders',
          method: 'get',
          params: {
            currentPage: currentPage.value,
            pageSize: pageSize.value
          }
        })
        
        if (response && response.records) {
          ordersList.value = response.records
          total.value = response.total || 0
          // 优化表格重新布局的时机
          await nextTick()
          setTimeout(() => {
            if (ordersTableRef.value) {
              ordersTableRef.value.doLayout()
            }
          }, 100)
        } else {
          ordersList.value = []
          total.value = 0
        }
      } catch (error) {
        ElMessage.error('获取订单列表失败')
        ordersList.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchOrders()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchOrders()
    }
    
    onMounted(() => {
      fetchOrders()
    })
    
    return {
      loading,
      currentPage,
      pageSize,
      total,
      ordersList,
      ordersTableRef,
      dialogVisible,
      currentOrder,
      getStatusType,
      getOrderTimeline,
      handleSizeChange,
      handleCurrentChange,
      handleDetail
    }
  }
}
</script>

<style scoped>
.orders-management {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  overflow: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table__cell) {
  padding: 8px 0;
}

.order-detail {
  padding: 20px;
}

.order-timeline {
  margin-top: 30px;
}

.order-timeline h4 {
  margin-bottom: 20px;
  color: #606266;
}
</style> 